﻿using System;
using System.Threading;
using System.Threading.Tasks;
using static System.Threading.Thread;
using static System.Console;

namespace Project_5
{
    /// <summary>
    /// 5.2 使用await 操作符获取异步任务结果
    /// </summary>
    public class Unit_5_02
    {
        public static void Go()
        {
            Task t = AsynchronyWithTPL();
            t.Wait();
            t = AsynchronyWithAwait();
            t.Wait();
        }

        static Task AsynchronyWithTPL()
        {
            int i = 1;
            Task<string> t = GetInfoAsync("Task 1");
            Task t2 = t.ContinueWith(task => WriteLine(t.Result),
                TaskContinuationOptions.NotOnFaulted);
            Task t3 = t.ContinueWith(task => WriteLine(t.Exception.InnerException),
                TaskContinuationOptions.OnlyOnFaulted);
            return Task.WhenAny(t2, t3);
        }

        static async Task AsynchronyWithAwait()
        {
            try
            {
                string result = await GetInfoAsync("Task 2");
                WriteLine(result);
            }
            catch (Exception e)
            {
                WriteLine(e);
                throw;
            }
        }

        static async Task<string> GetInfoAsync(string name)
        {
            await Task.Delay(TimeSpan.FromSeconds(2));
            return
                $"Task {name} is running on a thread id {CurrentThread.ManagedThreadId}." +
                $"Is thread pool thread：{CurrentThread.IsThreadPoolThread}";
        }
    }
}
